﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SHOP.Areas.Auth.Models;

namespace SHOP.Areas.Auth.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Auth/Login/

        //Kết nối dữ liệu
        AccountModelDataContext dataTable = new AccountModelDataContext();
        Constants Constants = new Constants();

        [HandleError]
        public ActionResult Index()
        {
            return View();
        }

        [HandleError, HttpPost]
        public ActionResult save()
        {
            string status = "success";
            string mess = "";

            //Update
            var id = (int)Session["id"];

            if (ModelState.IsValid)
            {
                var ListItem = dataTable.accounts.Single(b => b.id == id);

                if (Request.Form["password"] != null && Request.Form["password"] != "")
                    ListItem.password = Constants.md5(Request.Form["password"]);

                ListItem.fullname = Request.Form["fullname"];

                ListItem.phone = Request.Form["phone"].Trim();
                ListItem.address = Request.Form["address"];
                ListItem.random_key = Constants.md5(DateTime.Now.ToString());
                ListItem.changed = DateTime.Now;
                dataTable.SubmitChanges();

                status = "success";
                mess = "Cập nhật thành công";
            }
            else
            {
                status = "fail";
                mess = "Đăng nhập không thành công";
            }

            return Json(new { st = status, message = mess, auth = Session["auth"] });
        }

        [HandleError]
        public ActionResult login()
        {
            string status = "success";
            string mess   = "";

            string username = Request.Form["username"];
            string password = Constants.md5(Request.Form["password"]);
            int recCount = dataTable.accounts.Where("username = @0 AND password = @1", username, password).Count();
            
            if (recCount > 0)
            {
                var Account = dataTable.accounts.Where("username = @0", username).SingleOrDefault();

                Session["id"]       = Account.id;
                Session["email"]    = Account.email;
                Session["username"] = Account.username;
                Session["fullname"] = Account.fullname;
                Session["favorite"] = Account.favorite;
                Session["auth"]     = Account.auth;
                
                mess = "Đăng nhập thành công";
            }else{
                status = "fail";
                mess = "Đăng nhập không thành công";
            }

            return Json(new { st = status, message = mess, auth = Session["auth"] });
        }

    }
}
